<?php
namespace backend\models\course;
use backend\models\course\CourseType;
use backend\models\course\CourseBank;
use backend\models\course\CourseSource;
use backend\models\course\CourseCategory;
use backend\models\course\CourseSection;
use backend\models\course\CoursePeriod;
use backend\models\user\TeacherFrom;
use backend\models\Teacher;
use yii\data\Pagination;
use Yii;


/**
 * This is the model class for table "{{%edu_course}}".
 *
 * @property integer $course_id
 * @property string $course_name
 * @property string $course_thumb
 * @property integer $teacher_id
 * @property integer $price_status
 * @property string $course_price
 * @property integer $apply_num
 * @property integer $recruit_num
 * @property integer $type
 * @property integer $source_id
 * @property integer $teacher_from_id
 * @property integer $rank_id
 * @property integer $cate_id
 * @property string $describe
 * @property string $fit_crowd
 * @property string $result
 * @property integer $start_time
 * @property integer $end_time
 * @property integer $status
 * @property integer $add_time
 * @property integer $upd_time
 * @property integer $weight
 */
class Course extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%course}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['teacher_id','is_serialize', 'apply_num', 'recruit_num', 'type_id', 'source_id', 'teacher_from_id', 'rank_id', 'cate_id', 'start_time', 'end_time', 'status', 'add_time', 'upd_time', 'weight'], 'integer'],
            [['course_price'], 'number'],
            [['course_name'], 'string', 'max' => 100],
            [['course_thumb'], 'file','extensions' => 'jpg, gif, png,pneg'],
            [['describe', 'fit_crowd', 'result','open_date'], 'string', 'max' => 250],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'course_id' => 'Course ID',
            'course_name' => 'Course Name',
            'course_thumb' => 'Course Thumb',
            'teacher_id' => 'Teacher ID',

            'course_price' => 'Course Price',
            'apply_num' => 'Apply Num',
            'recruit_num' => 'Recruit Num',
            'type_id' => 'Type ID',
            'source_id' => 'Source ID',
            'teacher_from_id' => 'Teacher From ID',
            'rank_id' => 'Rank ID',
            'cate_id' => 'Cate ID',
            'describe' => '课程描述',
            'fit_crowd' => '适合人群',
            'result' => '能学到什么',
            'start_time' => 'Start Time',
            'end_time' => 'End Time',
            'status' => 'Status',
            'open_date'=>'开课时间',
            'add_time' => 'Add Time',
            'upd_time' => 'Upd Time',
            'weight' => 'Weight',
            'is_serialize'=> 'serialize',
        ];
    }


    //课程与课程类型关系
    public function getCategoty()
    {
        return $this->hasOne(CourseCategoty::className(),['cate_id'=>'cate_id']);
    }
    //课程与课程分类关系
    public function getType()
    {
        return $this->hasOne(CourseType::className(),['type_id'=>'type_id']);

    }
    //课程与等级关系
    public function getRank()
    {
        return $this->hasOne(CourseRank::className(),['rank_id'=>'rank_id']);
    }
    //课程与来源关系
    public function getSource()
    {
        return $this->hasOne(CourseSource::className(),['source_id'=>'source_id']);
    }
     //课程与教师关系
    public function getTeacher()
    {
        return $this->hasOne(Teacher::className(),['teacher_id'=>'teacher_id']);
    }

	//查询课程
	public function CourseSel($course_ids)
    {
		return $this->find()
				->where("course_id in ($course_ids)")
				->asArray()
				->all();
	}
	//修改图片
	public function CourseUpdateImg($course_id,$rootPath)
    {
		return $this->updateAll(['course_thumb' => $rootPath],'course_id=:course',[':course'=>$course_id]);
	}
	/**
	* 查询条数
	*/
	public function CourseCount($code)
    {
		return $this->find()
					->joinwith('teacher')
					->where($code)
					->count();
	}
	/**
	* 搜索查询
	*/
	public function CourseSearch($code,$pagination)
    {
		return $this->find()
				->joinwith('teacher')
				->joinwith('type')
				->where($code)
				->orderBy(['add_time'=>SORT_DESC])
				->offset($pagination->offset)
				->limit($pagination->limit)
				->asArray()
				->all();
	}

    /**
     * 获取课程目录
     */
    public static function CourseCatalog($id)
    {
        $section =CourseSection::find()->with('joint')->where(['course_id'=>$id])->asArray()->all();
            if ($section) {
                foreach ($section as $k => $v) {
                    foreach ($v['joint'] as $kk => $vv) {
                        $joint[] = $vv['joint_id'];
                    }
                }
                if (!empty($joint)) {
                    $joint_ids = implode(",", $joint);
                    $periods = CoursePeriod::find()->where("joint_id in($joint_ids)")->asArray()->all();
                    foreach ($section as $k => $v) {
                        foreach ($v['joint'] as $kk => $vv) {
                            foreach ($periods as $period) {
                                if ($period['joint_id'] == $vv['joint_id']) {
                                    $section[$k]['joint'][$kk]['period'][] = $period;
                                }
                            }
                        }
                    }
                }

            }
        return $section;
    }
    /**
     * 添加/编辑 章
     */
    public static function SectionAdd()
    {
        $request        = YII::$app->request;
        $course_id      = $request->post('course_id');
        //如果section_id有值 则为编辑
        if (!empty($request->post('section_id'))) {
           $section     = CourseSection::findOne($request->post('section_id'));
           $section     ->setAttributes($request->post());
           $re          = $section->save();
           return $course_id;
        }
        //添加章
        $section_count  = CourseSection::find()->where(['course_id'=>$course_id])->count();
        $section        = new CourseSection;
        $section  ->setAttributes($request->post());
        $section  ->section_num     = $section_count+1;
        $section  ->section_addtime = time();
        $re       = $section->save();
        return $course_id;

    }
    /**
     * 添加节
     */
    public static function JointAdd()
    {
        $request        = YII::$app->request;
        $course_id      = $request->post('course_id');
        //如果joint_id有值 则为编辑
        if (!empty($request->post('joint_id'))) {
           $joint       = CourseJoint::findOne($request->post('joint_id'));
           $joint       ->setAttributes($request->post());
           $re          = $joint->save();
           return $course_id;
        }
        $section_id     = $request->post('section_id');
        $joint_count    = CourseJoint::find()->where(['section_id'=>$section_id])->count();
        $joint  = new CourseJoint;
        $joint  ->setAttributes($request->post());
        $joint  ->joint_num     = $joint_count+1;
        $joint  ->joint_addtime = time();
        $re     = $joint->save();
        return $course_id;
    }
    /**
     * 添加课时
     */
    public static function PeriodAdd()
    {

        $request      = YII::$app->request;
        $course_id    = $request->post('course_id');
        $joint_id     = $request->post('joint_id');
        //获取课时数量
        $period_count = CoursePeriod::find()->where(['joint_id'=>$joint_id])->count();
        $data         = $request->post();
        if ($data['period_id']) {
            $period       = CoursePeriod::findOne($data['period_id']);
        }else{
            isset($data['period_id']);
            $period       = new CoursePeriod;
        }

        if ($data['movie_name']) {
            $data['movie_url'] = 'videos.bwphp.com/webupload/upload/'.$data['movie_name'];
        }
        if ($data['open_time'] || $data['end_time']) {
            $data['open_time'] = strtotime($data['open_time']);
            $data['end_time'] = strtotime($data['end_time']);
        }
        $period  ->setAttributes($data);
        $period  ->period_num     = $period_count+1;
        $period  ->period_addtime = time();
        $period  ->period_updtime = time();
        $aa      = $period->save();
        /*$ftp = new Ftp;
        $re= $ftp->up_file('./webupload/server/upload/'.$movie_file,'movie/'.$movie_file); // 上传文件
        var_dump($re);die;*/
        return $course_id;
    }

    /**
     * 课程列表
     */
    public function CourseList($keyword)
    {
        $request = Yii::$app->request;
        $cond = "1=1 and edu_course.status=1";
        if ($keyword['type']) {
           (int)$type = $keyword['type'];
           $cond .= " and edu_course.type_id=$type";
        }
        if ($keyword['rank']) {
            (int)$rank = $keyword['rank'];
           $cond .= " and edu_course.rank_id=$rank";
        }
        if ($keyword['source']) {
            (int)$source = $keyword['source'];
           $cond .= " and edu_course.source_id=$source";
        }
        if ($keyword['cate']) {
            (int)$cate = $keyword['cate'];
            $cond .= " and edu_course.cate_id=$cate";
        }

        $pagination = new Pagination([
            'defaultPageSize' => 16,
            'totalCount' => $this::find()
                                    ->where($cond)
                                    ->count(),
        ]);

        $course = $this::find()
                            //->select(['edu_course.*','edu_course_rank.rank_name','edu_course_rank.rank_id','edu_teacher_info.*'])
                            //->joinwith("teacher")
                            ->joinwith('rank')
                            ->where($cond)
                            ->offset($pagination->offset)
                            ->limit($pagination->limit)
                            ->orderBy('add_time desc')
                            ->asArray()->all();
                            //->createCommand()->getRawSql();
                            //echo $course;die;
        /*if ($course) {
           foreach ($course as $k => $v) {
            $from_id[] =  $v['teacher']['from_id'];
            }
            //删除相同id
            $from_id = array_unique($from_id);
            $from_id = implode(",", $from_id);
            $froms = TeacherFrom::find()->where("from_id in ($from_id)")->asArray()->all();
            foreach ($course as $k => $v) {
                foreach ($froms as $kk => $from) {
                    if ($v['teacher']['from_id'] == $from['from_id']) {
                        $course[$k]['teacher']['teacher_from']=$from['from_name'];
                    }
                }
            }
        }*/
        $course['pagination'] = $pagination;
        return $course;
    }

    /**
     * 课程详情
     */
    public function CourseDetail($course_id)
    {
        //$cond  = "'edu_course.course_id'=$course_id";
        $course  = $this::find()
                            ->joinwith("teacher")
                            ->joinwith('rank')
                            ->where("course_id=$course_id")
                            ->asArray()->one();
        $from_id = $course['teacher']['from_id'];
        $from    = TeacherFrom::find()->where("from_id=$from_id")->asArray()->one();
        $course['teacher']['teacher_from']=$from['from_name'];
        return $course;
    }

	/* 新增课程数  今日 */
    static public function TodayCourse($today_start,$today_end)
	{
		return Course::find()
				->where("add_time>= :today_start and add_time<= :today_end",
				[':today_start'=>$today_start,':today_end'=>$today_end])
				->count();
	}

	/* 新增课程数  昨日 */
	static public function YesterdayCourse($yesterday_start,$yesterday_end)
	{
		return Course::find()
				->where("add_time>= :yesterday_start and add_time<= :yesterday_end",
				[':yesterday_start'=>$yesterday_start,':yesterday_end'=>$yesterday_end])
				->count();
	}

	/* 加入学习数  今日 */
	static public function TodayStudynum($today_start,$today_end)
	{
		return Course::find()
				->where("add_time>= :today_start and add_time<= :today_end",
				[':today_start'=>$today_start,':today_end'=>$today_end])
				->sum("apply_num");
	}

	/* 加入学习数  昨日 */
	static public function YesterdayStudynum($yesterday_start,$yesterday_end)
	{
		return Course::find()
				->where("add_time>= :yesterday_start and add_time<= :yesterday_end",
				[':yesterday_start'=>$yesterday_start,':yesterday_end'=>$yesterday_end])
				->sum("apply_num");
	}

	/*课程总数  今日*/
	static public function TodayAllcourse()
	{
		return Course::find()
				->count();
	}

	/*课程总数  昨日*/
	static public function YseterdayAllcourse($yesterday_end)
	{
		return Course::find()
				->where("add_time<= :yesterday_end",
				[':yesterday_end'=>$yesterday_end])
				->count();
	}

	/* 直播课程 */
	static public function Directmessage($limit)
	{
		return Course::find()
				->where(" type_id = 11 and status = 1")
				->orderBy("weight desc")
				->limit($limit)
				->asArray()
				->all();
	}

	/* 视频课程 */
	static public function Videomessage($limit)
	{
		return Course::find()
				->where(" type_id = 2 and status = 1")
				->orderBy("weight desc")
				->limit($limit)
				->asArray()
				->all();
	}
	/*
	 *当前老师下所有的课程数量
	*/
	public function TeacherCourseCount($code)
	{
		return $this->find()
					->where($code)
					->count();
	}
	/**
	* 当前老师下所有的课程
	*/
	public function TeacherCourse($code,$pagination)
    {
		return $this->find()
				->where($code)
				->orderBy(['add_time'=>SORT_DESC])
				->offset($pagination->offset)
				->limit($pagination->limit)
				->asArray()
				->all();
	}
    /**
     * 课程推荐
     */
    static public function Coursermd()
    {
       return self ::find()
                    ->joinwith("teacher")
                    ->limit(3)
                    ->orderBy(['apply_num'=>SORT_DESC])
                    ->asArray()
                    ->all();
    }


}
